var stats = new Stats()
function initStats() {
  stats.setMode(0)

  stats.domElement.style.position = 'absolute'
  stats.domElement.style.left = '20px'
  stats.domElement.style.top = '30px'

  document.getElementById('statsOutput').appendChild(stats.domElement)

  return stats
}

initStats()
// 创建场景
var scene = new THREE.Scene()

// 创建照相机 参数 距离, 宽高比,相机视锥体的近平面,相机视锥体的远平面
var camera = new THREE.PerspectiveCamera(
  40,
  window.innerWidth / window.innerHeight,
  0.8,
  600
)

camera.position.x = -30
camera.position.y = 40
camera.position.z = 30
camera.lookAt(scene.position)

// 渲染器
var renderer = new THREE.WebGLRenderer()

// 设置渲染器颜色
renderer.setClearColor(new THREE.Color(0xeeeeee))
// 设置渲染器尺寸
renderer.setSize(window.innerWidth, window.innerHeight)
// 阴影显示
renderer.shadowMapEnabled = true

// 显示坐标轴
// var axes = new THREE.AxisHelper(20)
// scene.add(axes)

// 设置平面大小
var planeGeometry = new THREE.PlaneGeometry(60, 20, 1, 1)
// 设置平面颜色
var planeMaterial = new THREE.MeshBasicMaterial({ color: 0xcccccc })
var plane = new THREE.Mesh(planeGeometry, planeMaterial)

plane.rotation.x = -0.5 * Math.PI

plane.position.x = 15
plane.position.y = 0
plane.position.z = 0

// 阴影显示接受
plane.receiveShadow = true

scene.add(plane)

// cub 立方体
var cubeGeometry = new THREE.BoxGeometry(4, 4, 4)
var cubeMaterial = new THREE.MeshBasicMaterial({
  color: 0xff0000,
  // 3d线性显示
  // wireframe: true,
})
var cube = new THREE.Mesh(cubeGeometry, cubeMaterial)

// 位置设置
cube.position.x = 10
cube.position.y = 4
cube.position.z = 4
cube.castShadow = true
scene.add(cube)

// 球体
var sphereGeometry = new THREE.SphereGeometry(4, 20, 20)
var sphereMaterial = new THREE.MeshBasicMaterial({
  color: 0x7777ff,
  // wireframe: true,
})
var sphere = new THREE.Mesh(sphereGeometry, sphereMaterial)

sphere.position.x = 8
sphere.position.y = 4
sphere.position.z = -4

sphere.castShadow = true

scene.add(sphere)

// 添加聚光灯
var spotLight = new THREE.SpotLight(0xffffff)
spotLight.position.set(-40, 60, -10)
spotLight.castShadow = true
scene.add(spotLight)

document.getElementById('main').appendChild(renderer.domElement)
renderer.render(scene, camera)

var controls = new (function () {
  this.rotationSpeed = 0.02
  this.boundcingSpeed = 0.03
})()

var gui = new dat.GUI()
gui.add(controls, 'rotationSpeed', 0, 0.5)
gui.add(controls, 'boundcingSpeed', 0, 0.5)

function renderScene() {
  stats.update()

  cube.rotation.x += controls.rotationSpeed
  cube.rotation.y += controls.rotationSpeed
  cube.rotation.z += controls.rotationSpeed

  step += controls.boundcingSpeed
  sphere.position.x = 20 + 10 * Math.cos(step)
  sphere.position.y = 2 + 10 * Math.abs(Math.cos(step))

  requestAnimationFrame(renderScene)
  renderer.render(scene, camera)
}

var step = 0
renderScene()
